package org.visionlibrary.image.filters.resampling;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class BilinearInterpolation extends AbstractFilter {
	protected int newWidth = 1024;
	protected int newHeight = 1024;

	public BilinearInterpolation() {
		this(128, 128);
	}

	public BilinearInterpolation(int newWidth, int newHeight) {
		this.newWidth = newWidth;
		this.newHeight = newHeight;
	}

	public TiledImage applyFilter(TiledImage src, TiledImage dest)
			throws IllegalArgumentException {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (dest != null)
			throw new IllegalArgumentException(
					"this only works with construction:\ndest = filter.applyFilter( src, null );");

		dest = (new ImageFactory()).createCompatibleImage(src, newWidth,
				newHeight);

		double ratiox = (src.getWidth()-1) * 1.0d / newWidth * 1.0d;
		double ratioy = (src.getHeight()-1) * 1.0d / newHeight * 1.0d;

		int maxX = dest.getWidth();
		int maxY = dest.getHeight();
		for (int ch = 0; ch < src.getNumBands(); ch++)
			for (int x = 0; x < maxX; x++)
				for (int y = 0; y < maxY; y++) {
					double i = x * ratiox;
					double j = y * ratioy;
					int k = (int) i;
					int l = (int) j;
					
					double a = i - k;
					double b = j - l;
					double Fa0 = (1 - a) * src.getSample(k, l, ch) + a
							* src.getSample(k + 1, l, ch);
					double Fa1 = (1 - a) * src.getSample(k, l + 1, ch) + a
							* src.getSample(k + 1, l + 1, ch);
					double Fab = (1 - b) * Fa0 + b * Fa1;
					dest.setSample(x, y, ch, ((int) Fab));
				}

		return dest;
	}

	public int getNewHeight() {
		return newHeight;
	}

	public int getNewWidth() {
		return newWidth;
	}

	public void setNewHeight(int newHeight) {
		this.newHeight = newHeight;
	}

	public void setNewWidth(int newWidth) {
		this.newWidth = newWidth;
	}
}
